import {createRouter, createWebHistory, createWebHashHistory} from "vue-router"

import Login from "@/components/Login.vue"
import Home from '@/components/Home.vue'
import FirstPage from "@/components/page/system/FirstPage.vue";
import { defineAsyncComponent} from 'vue'

 const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            name: "home",
            path: '/',
            component: Home,
            children: [
                {
                    name: 'firstPage',
                    path: '/system/firstPage',
                    component: FirstPage,
                    meta: {
                        title: '首页'
                    },
                }
            ]
        },
        {
            path: '/login',
            component: Login
        }
    ]
});
router.beforeEach((to, from, next) => {
    if (to.matched.length === 0) {
        next({path: from.path, replace: true, query: {date: new Date().getTime()}});
    } else {
        next();
    }
});

//加载page动态路由【只是构建菜单路由权限】【只构建两层作为菜单路由】
const components = import.meta.glob('@/components/*/*/*.vue');
let asyncRoutes = [];
function firstLetterToLowerCase(path:string) {
    const parts = path.split('/');
    if (parts.length > 1) {
        const lastPart:any = parts.pop();
        parts.push(lastPart[0].toLowerCase() + lastPart.slice(1));
    }
    return parts.join('/');
}
for (const path in components) {
    let  componentName;
    if(!path.indexOf("page")){
        componentName = path;
    }else {
        componentName = path.substring(path.indexOf("page") + "page".length ,path.length)
            .replace(/\.\w+$/, '');
    }
    const cpm:any = components[path];
    const route = {
        path: firstLetterToLowerCase(componentName),
        component: defineAsyncComponent(cpm)
    };
    asyncRoutes.push(route);
}

export  {router,asyncRoutes}